package quertz.job.service;

import org.quartz.*;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import utils.EnvironmentUtils;

import java.text.ParseException;

/**
 * Author: Jason Wu
 * Date  : 2013-09-27
 */
@Service
public class JobManageService {

    private static final Logger LOGGER = LoggerFactory.getLogger(JobManageService.class);

    public void launchJob(ApplicationContext applicationContext) throws Exception {
        String serviceBeanName = "pushJobImpl";
        String jobId = "pushJob";
        SyncJob syncJob = applicationContext.getBean(serviceBeanName, SyncJob.class);
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        String jobGroup = String.format("%s-group", jobId);
        JobKey jobKey = new JobKey(jobId, jobGroup);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        if (jobDetail == null) {
            jobDetail = createJobDetail(jobKey);
            jobDetail.getJobDataMap().put("serviceBeanName", syncJob);
            scheduler.scheduleJob(jobDetail, createTrigger(jobId));
            scheduler.start();
            LOGGER.info(String.format("Launching a new job:[%s]", jobId));
        } else {
            scheduler.resumeJob(jobKey);
            LOGGER.info(String.format("Job resuming :[%s]", jobId));
        }
    }

    private Trigger createTrigger(String jobId) throws ParseException {
        CronTriggerImpl trigger = new CronTriggerImpl();
        trigger.setName(String.format("%s-trigger", jobId));
        trigger.setCronExpression(EnvironmentUtils.getJobCronExpress());
        return trigger;
    }

    private JobDetail createJobDetail(JobKey jobKey) {
        JobDetailImpl jobDetail = new JobDetailImpl();
        jobDetail.setKey(jobKey);
        jobDetail.setJobClass(JobImpl.class);
        JobDataMap jobDataMap = new JobDataMap();
        jobDetail.setJobDataMap(jobDataMap);
        return jobDetail;
    }
}
